﻿using System;
using System.Collections.Generic;
using ShapeManager;

namespace Commands
{
    /// <summary> 撤销管理 </summary>
    public class UndoManager
    {
        int nextUndo;               //下一个撤销
        ShapeList shapeList;        //形状列表
        List<ICommand> historyList; //历史列表

        public UndoManager(ShapeList shapeList)
        {
            this.shapeList = shapeList;
            ClearHistory();
        }
        /// <summary> 添加命令到历史列表 </summary>
        public void AddCommandToHistory(ICommand command)
        {
            TrimHistoryList();
            historyList.Add(command);
            Console.WriteLine("命令添加");
            nextUndo++;
        }
        /// <summary> 剔除记录列表 </summary>
        private void TrimHistoryList()
        {
            // 若历史列表中无任何项目，直接退出。
            if (historyList.Count == 0)
            {
                return;
            }
            // 如果“NextUndo”指针指向列表中的最后一个项目，直接退出。
            if (nextUndo == historyList.Count - 1)
            {
                return;
            }
            // 删除“下一个撤销操作”指针以下的所有项目
            for (int i = historyList.Count - 1; i > nextUndo; i--)
            {
                historyList.RemoveAt(i);
            }
        }
        /// <summary> 清空历史 </summary>
        public void ClearHistory()
        {
            historyList = new List<ICommand>();
            nextUndo = -1;
        }


        /// <summary> 撤销 </summary>
        public void Undo()
        {
            if (!CanUndo())
            {
                Console.WriteLine("没有可撤销的命令.");
                return;
            }
            if (historyList.Count > 0)
            {
                ICommand command = historyList[nextUndo];
                command.Undo(shapeList);
                nextUndo--;
                Console.WriteLine("命令撤销");
            }
        }
        /// <summary> 重做  </summary>
        public void Redo()
        {
            if (!CanRedo())
            {
                Console.WriteLine("没有可重做的命令。");
                return;
            }
            if (historyList.Count > 0)
            {
                int itemToRedo = nextUndo + 1;
                ICommand command = historyList[itemToRedo];
                command.Redo(shapeList);
                nextUndo++;
                Console.WriteLine("命令重做");
            }
        }
        /// <summary> 可以撤销  </summary>
        public bool CanUndo()
        {
            if (nextUndo < 0 ||
               nextUndo > historyList.Count - 1)
            {
                return false;
            }
            return true;
        }
        /// <summary> 可以重做  </summary>
        public bool CanRedo()
        {
            if (nextUndo == historyList.Count - 1)
            {
                return false;
            }
            return true;
        }
        
    }
}
